import { ActivatedRouteSnapshot, CanDeactivate, Router, RouterStateSnapshot } from '@angular/router';
import { ComponentFactoryResolver, Injectable } from '@angular/core';
import { MyModalHelper } from '@core/my-modal.helper';
import { LeaveConfirmComponent } from '@shared/leave-confirm/leave-confirm.component';
import { ImgMaterialEditComponent } from '../../routes/img-material/img-material-edit/img-material-edit.component';

@Injectable()
export class CanDeactivateVideoGuardActivate implements CanDeactivate<ImgMaterialEditComponent> {
  constructor(private modalHelper: MyModalHelper,
              private componentFactoryResolver: ComponentFactoryResolver,
              private router: Router) {
  }

  canDeactivate(
    component: ImgMaterialEditComponent,
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot,
  ): Promise<boolean> | boolean {

    let isDirty = false;
    let text = '离开本页面将不会保存您编辑修改的信息，确认离开吗？';
    if (component.validateForm.dirty || component.componentDirty) {
      isDirty = true;
    }
    if (component.uploading) {
      text = '视频上传中，现在离开本页面将不会保存您修改的视频信息，确认离开吗？';
      isDirty = true;
    }
    if (!isDirty) {
      //未做修改 直接离开
      return true;
    }
    return new Promise((resolve, reject) => {
      this.modalHelper.open(LeaveConfirmComponent, { tipText: text }, 520, {
        nzTitle: '提示',
      }).subscribe(result => {
        // console.log(result);
        if (result) {//离开
          return resolve(true);
        } else {//继续编辑
          return resolve(false);
        }
      }, (error) => {
        console.error('弹窗回调出错：', error);
        return resolve(false);
      });
    });

  }
}
